
function stretchElements(list){
	$.each(list,function(i, n){
		var parent_width = $("#" + n).parent().width() - 10;
		parent_width = parent_width + "px";
		$("#" + n).width(parent_width);
	});
}



//pauls function.  Works Great!
function validDate(date){
	//var for required element error message.
	var date_message = " <span id='error_message'>Must be a valid date.</span>";
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//pauls date validator in action with jquery.
	var validator = new pdv();
	if (date.value.length > 0) {
		if (validator.IsSQLServerDate(date.value)){
			date.value = validator.DisplayDate(date.value, 'mm/dd/yyyy');			
		}else{		
			$("#error").show();
			$("#" + date.id + " ~ img").after(date_message);
			$("#" + date.id).addClass('textbox_error');	
		}
	}	
}



function validateElements(list){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;
	
	//var for required element error message.
	var require_message = " <span id='error_message'>Field is required.</span>";
	
	//these fields are require on form.
	var required_fields = ["PlanDate"];
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//if fields in the required_fields variable are empty this error is triggered.
	$.map(required_fields,function(field){
		if( !$("#" + field).val() )	{
			error_count++;
			$("#error").show();
			$("#" + field + " ~ img").after(require_message);
			$("#" + field).addClass('textbox_error');
		}
	});
		
	//if no errors in validation, well... the data is valid!
	if(error_count){return false;}else{return true;}
}



function bindElements(){
	//binds IADL textboxes to total up entered values.
	//idalTotals();
	$("#PreparingMeals, #DoingHouseWork, #DoingLaundry, #DoingShopping").bind('change', function(){
		idalTotals();			   
	});	
	
	//datepicker for date selection
	$("#PlanDate, #ElderSignatureDate:not(input[type='hidden']), #StaffSignatureDate:not(input[type='hidden']), #SupervisorSignatureDate:not(input[type='hidden'])").datepicker({ 
		dateFormat: 'mm/dd/yy', changeYear: true, changeMonth: true, yearRange: '1900:2010', autoSize: true,
		prevText: 'Earlier', nextText: 'Later', showOn: 'button', 
		buttonImage: '/CFIDE/scripts/ajax/resources/cf/images/DateChooser.png', buttonImageOnly: true,
		onClose: function(dateText, inst) { $(this).focus() }
	});
	
	$("#PlanDate").bind("blur change load submit", function(){
		var eval_date = new EvalDate( );
		try{
			$("#EvalDate, #EvalDateShow").val( eval_date.funcEvalDateSet( $("#PlanDate").val() ) );
		}catch(err){}
	});
	
	//strech textarea's to fill up td.
	stretchElements(["Comments"]);
	
	//binds change event to getDataById.  This is to populate form data.
	$("#elder").bind("change", function(){
		loadElder();
	});
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#new_serviceplan").bind("click", function(){
		if ( validateElements() ){
			if( $("#serivce_plans option:selected").val() == '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=add_service_plan', 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#edit_serviceplan").bind("click", function(){
		if ( validateElements() ){
			if( $("#serivce_plans option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=edit_service_plan', 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#delete_serviceplan").bind("click", function(){
		if ( validateElements() ){
			if( $("#serivce_plans option:selected").val() != '-1' ){
				$("#myform").attr({'action': 'api.cfm?api=delete_service_plan&id=' + 
								  $("#serivce_plans option:selected").val(), 'method':'POST'});
				$("#myform").submit();
			}
		}
	});
	
	//binds plan drop down to load plans
	$("#serivce_plans").bind('change', function(){
		window.location.href="serviceplan.cfm?ElderID=" + $("#elder option:selected").val() + 
			"&PlanID=" + $("#serivce_plans option:selected").val();
		//setting session variable that holds current elder selected
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );
	});
	
	
	if( $("#serivce_plans option:selected").val() == -1 ){
		$("#new_serviceplan").show();
		$("#edit_serviceplan").hide();
		$("#delete_serviceplan").hide();
	}else{
		$("#new_serviceplan").hide();
		$("#edit_serviceplan").show();
		$("#delete_serviceplan").show();
	}

}


function idalTotals(){
	var iadl_total = 0;
	
	//add all the iadl options together.
	iadl_total = parseInt($('#PreparingMeals option:selected').val()) + parseInt($('#DoingHouseWork option:selected').val()) + 
		parseInt($('#DoingShopping option:selected').val()) + parseInt($('#DoingLaundry option:selected').val());
	
	//send dropdown totals to span that displays the total iadl
	$("#iadl_total").text(iadl_total);
	
	//acuity level.  This is noob code.  Do it better later.
	/*var acuity_level_total = {
		16 : "Homebound",
		12 : "Disabled", 13 : "Disabled", 14 : "Disabled", 15 : "Disabled",
		8 : "Semi-Independent", 9 : "Semi-Independent", 10 : "Semi-Independent", 11 : "Semi-Independent",
		4 : "Independent", 5 : "Independent", 6 : "Independent", 7 : "Independent"
	};*/
	
	//var acuity_level_dropdown = {"Homebound" : 2, "Disabled" : 3, "Semi-Independent" : 4, "Independent": 5};
	
	//send acuity_totals the total iadl value and the acuity_level_totals dictionary will display the correct Acuity Level.
	//$("#PriorityID").val(acuity_level_dropdown[acuity_level_total[iadl_total]]).attr('selected');
}



function loadElder(){
	//takes value of selected option in the elder dropdown and passes it to the function that fills the form.
	if($("#elder option:selected").val() != -1){
		window.location.href="serviceplan.cfm?ElderID=" + $("#elder option:selected").val();
		
		//setting session variable that holds current elder selected
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );
		
	}
	else{
		window.location.href="serviceplan.cfm?ElderID=" + $("#elder option:selected").val() + "&PlanID=-1";
		var session_elder_id = new sse();
		session_elder_id.funcSetSessionElderID( $("#elder option:selected").val() );		
	}	
}



function clearElements(){
	//reset all textboxes
	$(":input:not(input[type='button']):not(input[type='hidden']):not(input[id='date_of_contact'])" + 
		":not(select[id='serivce_plans']):not(select[id='elder']):not(input[id='sign_date'])").val("");
}



function submitForm(obj, api){
	//ajax POST to add a provider to database.
	$.ajax({
		type:'POST', url:'api.cfm?api=' + api, dataType: 'json', async: true, data: obj,
		success: function() {return true;},
		complete: function(){
			return true;
		},
		error: function(){return false;}
	});
}


//ajax GET to retrive data from database.
var getDataById = function(api, id){	
	var data = {};	
	var api_url = "api.cfm?api=" + api + ( (id) ? "&id=" + id : "" );	
	
	if (id != -1){
		$.ajax({
		type:'GET', url: api_url, dataType: 'json', async: false,
			success: function(json) { data = json; },
			complete: function() {  },
			error: function() {  }
		});
	}	
	return data;
};


$(function(){
	bindElements();	
	idalTotals();
});